package com.lemons.hackaton.app.data;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;

import com.lemons.hackaton.app.Application;
import com.lemons.hackaton.app.util.FindUtils;
import com.lemons.hackaton.obj.Journey;
import com.lemons.hackaton.obj.Person;

public class DocxReader {
	
	public void processDocFiles(String path) throws InvalidFormatException {
		File dir = new File(path);
		FileFilter fileFilter = new WildcardFileFilter("*.docx");
		File[] files = dir.listFiles(fileFilter);
		
		for(int i = 0; i < files.length; i++) {
			readDocument(files[i].toString());
		}
	}
	
	private void readDocument(String filePath) throws InvalidFormatException {
		try {
			
			XWPFDocument docx = new XWPFDocument(OPCPackage.openOrCreate(new File(filePath)));  
			XWPFWordExtractor wx = new XWPFWordExtractor(docx);
			String text = wx.getText();  
			
			Person p = null;
			p = Application.journey.getPerson(FindUtils.findPersonInText(text, Journey.personDictionary));
			//System.out.println("p1:" +p);
			if (p != null) {
				p.addToBudget(Float.valueOf(FindUtils.findMoneyInText(text).replace("USD", "")));
				//System.out.println("p2:" +p);
				for(String item : FindUtils.findActivitiesInText(text, Journey.activityDictionary)) {
					p.setActivity(item);
					//System.out.println("p3:" +p + " In " + filePath);
				}
			}
			
			
		} catch (FileNotFoundException exep) {

		} catch (IOException e) {
			// TODO: handle exception
		}
	}
}
